package cn.bonoon.kernel.expression.results;

import cn.bonoon.kernel.events.ReadEvent;
import cn.bonoon.kernel.expression.ExpressionValue;
import cn.bonoon.kernel.expression.StandardExpressionParser;
import cn.bonoon.kernel.util.StringHelper;

public class RequestExpressionValue implements ExpressionValue{
	
	private final String parameterName;
	private final String type;
	
	public RequestExpressionValue(StandardExpressionParser seParser, String parameterName, String type){
		this.parameterName = parameterName;
		if(null == type){
			this.type = "NULL";
		}else{
			this.type = type;
		}
	}

	public RequestExpressionValue(StandardExpressionParser seParser, String parameterName){
		this(seParser, parameterName, null);
	}

	@Override
	public Object value(ReadEvent event, Object defaultValue) {
		String val = event.getString(parameterName);
		switch (type) {
		case "I":
			if(null != val){
				return StringHelper.toInteger(val);
			}
			Object obj = event.getAttributeObject(parameterName);
			if(obj instanceof Integer){
				return obj;
			}else if(obj instanceof Number){
				return ((Number)obj).intValue();
			}
			return -1;
		case "J":
			return StringHelper.toLong(val);
		case "F":
			return StringHelper.toFloat(val);
		case "D":
			return StringHelper.toDouble(val);
		case "Z":
			return Boolean.valueOf(val);
		case "B":
			return StringHelper.toByte(val);
		case "C":
			return StringHelper.toChar(val);
		case "S":
			return StringHelper.toShort(val);
		case "DT":
			return StringHelper.toDatetime(val);
		}
		return val;
	}
}
